package com.itxh.mvc.mapping;

import com.itxh.aware.BeanFactoryAware;
import com.itxh.factory.BeanFactory;
import com.itxh.factory.DefaultListableBeanFactory;
import com.itxh.init.InitializingBean;
import com.itxh.model.BeanDefinition;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanNameUrlHandlerMapping implements HandlerMapping, BeanFactoryAware, InitializingBean {
    private Map<String,Object> handlerMappings = new HashMap<>();

    private DefaultListableBeanFactory beanFactory;

    // 如何对handlerMappings进行初始化


    @Override
    public Object getHandler(HttpServletRequest request) {
        String uri = request.getRequestURI();
        if (uri == null || "".equals(uri)){
            return  null;
        }

        return handlerMappings.get(uri);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;
    }

    @Override
    public void afterPropertiesSet() {
        List<BeanDefinition> beanDefinitions = beanFactory.getBeanDefinitions();
        for (BeanDefinition bd : beanDefinitions) {
            String name = bd.getId();
            if (name.startsWith("/")){
                handlerMappings.put(name,beanFactory.getBean(name));
            }
        }
    }
}
